import http from "@/utils/http.ts";
import {R} from "@/api/common.ts";
import router from "@/router/router.ts";

enum Login {
    login = "user/login",
    logout = "user/logout",
    register = "user/register",
}

export interface Data {
    id: number;
    userName: string;
    email: string;
    createTime: string;
    updateTime: string;
    status: number;
    token: Token;
}

export interface Token {
    tokenName: string;
    tokenValue: string;
    isLogin: boolean;
    loginId: string;
    loginType: string;
    tokenTimeout: number;
    sessionTimeout: number;
    tokenSessionTimeout: number;
    tokenActiveTimeout: number;
    loginDevice: string;
    tag: any;
}

/**
 * 登录验证码
 * @param email 邮箱
 */
export function loginSend(email: string) {
    return http<R<null>>({
        url: `${Login.login}/${email}`,
        method: "get",
    })
}

/**
 * 登录
 * @param data 邮箱和验证码
 */
export function login(data: { email: string, code: string }) {
    return http<R<Data>>({
        url: Login.login,
        method: "post",
        data,
    })
}

/**
 * 注册
 * @param data
 */
export function register(data: { email: string, code: string, userName: string }) {
    return http<R<Data>>({
        url: Login.register,
        method: "post",
        data,
    })
}

/**
 * 登出
 */
export function logout() {
    return http<R<null>>({
        url: Login.logout,
        method: "get",
    })
}

/**
 * 注册验证码
 * @param email
 */
export function registerSend(email: string) {
    return http<R<null>>({
        url: `${Login.register}/${email}`,
        method: "get",
    })
}

export function saveToken(name: string, token: string) {
    localStorage.setItem("tokenName", name)
    localStorage.setItem(name, encodeURIComponent(JSON.stringify(token)))
    router.push("/index")
}

export function getToken() {
    let key = localStorage.getItem("tokenName");
    return {
        value: JSON.parse(decodeURIComponent(localStorage.getItem(key))),
        name: key
    }
}

export function removeToken() {
    let key = localStorage.getItem("tokenName");
    localStorage.removeItem(key);
    localStorage.removeItem("tokenName");
    router.push("/login")
}




